import os
import subprocess
import threading
import tkinter as tk
from tkinter import ttk
from typing import Dict, List
import webbrowser
from urllib.parse import urljoin
from .search_bar import SearchBar
# from ..api.git_repos import find_git_repos, get_remote_urls


class GitRepoBrowser(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.base_path = r"C:\Users\houzh\Developing"
        self.ignored_paths = []
        # self.repo_list = self.find_git_repos()
        self.create_widgets()
        self.data = []

    def find_git_repos(self):
        # 这里调用 find_git_repos_2 函数，获取仓库列表
        return find_git_repos(self.base_path, self.ignored_paths)

    def create_widgets(self):
        self.search_bar = SearchBar(self, self.on_filter)
        self.search_bar.pack(side="top", fill="x")
        self.button = ttk.Button(self, text="开始运算", command=self.populate_tree)
        self.button.pack()
        self.button_open_in_vscode = ttk.Button(
            self, text="Open in VSCode", command=self.open_in_vscode
        )
        self.button_open_in_vscode.pack()
        self.tree = ttk.Treeview(
            self, columns=("Repo Name", "Local Path", "Remote Branch")
        )
        self.tree.heading("#0", text="Number")
        self.tree.heading("#1", text="仓库本地路径")
        self.tree.heading("#2", text="仓库远程地址")

        self.tree.column("#0", width=50, anchor="center")
        # self.tree.column("#1", width=150, anchor="center")
        self.tree.column("#1", width=300, anchor="center")
        self.tree.column("#2", width=300, anchor="center")
        self.tree.column("#3", width=100, anchor="center")

        self.tree.pack(expand=True, fill="both")

        data = [
            {
                "text": "1",
                "values": ["C:\\Users\\houzh\\Developing\\PyBirdViewCode", ""],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "gitee - git@gitee.com:hzy15610046011/py-bird-view-code.git",
                        ],
                        "children": [],
                    },
                    {
                        "text": "",
                        "values": [
                            "",
                            "origin - https://github.com/hzyrc6011/MetronomeStatic.git",
                        ],
                        "children": [],
                    },
                ],
            },
            {
                "text": "2",
                "values": ["C:\\Users\\houzh\\Developing\\ixmp4", ""],
                "children": [
                    {
                        "text": "",
                        "values": ["", "origin - https://github.com/iiasa/ixmp4.git"],
                        "children": [],
                    }
                ],
            },
            {
                "text": "3",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\C\\STM32_RC_Transmitter",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "origin - https://gitee.com/J20RC/STM32_RC_Transmitter.git",
                        ],
                        "children": [],
                    }
                ],
            },
            {
                "text": "4",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\C\\sqlite3",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "origin - https://gitee.com/big_thirdparty/sqlite3.git",
                        ],
                        "children": [],
                    }
                ],
            },
            {
                "text": "5",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\C\\lua",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": ["", "origin - https://github.com/lua/lua.git"],
                        "children": [],
                    }
                ],
            },
            {
                "text": "6",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\transponder",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "origin - https://gitee.com/stlswm/transponder.git",
                        ],
                        "children": [],
                    }
                ],
            },
            {
                "text": "7",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\go_comm_with_dll",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "myorigin - https://gitee.com/hzy15610046011/GolangCallDLLDemo.git",
                        ],
                        "children": [],
                    }
                ],
            },
            {
                "text": "8",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\guiguzi_pack\\programbak",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "myorigin - https://gitee.com/hzy15610046011/emergent_monitor_proj.git",
                        ],
                        "children": [],
                    },
                    {
                        "text": "",
                        "values": [
                            "",
                            "official - https://git.veypi.com/Iain/Guiguzi.git",
                        ],
                        "children": [],
                    },
                    {
                        "text": "",
                        "values": ["", "origin - git@git.veypi.com:Iain/Guiguzi.git"],
                        "children": [],
                    },
                ],
            },
            {
                "text": "9",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\guiguzi_pack\\program",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "origin - https://gitee.com/hzy15610046011/guiguzi",
                        ],
                        "children": [],
                    }
                ],
            },
            {
                "text": "10",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\guiguzi_pack\\program\\node",
                    "",
                ],
                "children": [],
            },
            {
                "text": "11",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\Guiguzi",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "official - https://git.veypi.com/Iain/Guiguzi.git",
                        ],
                        "children": [],
                    }
                ],
            },
            {
                "text": "12",
                "values": [
                    "C:\\Users\\houzh\\Developing\\A. Developing-backup\\Go\\cachego",
                    "",
                ],
                "children": [
                    {
                        "text": "",
                        "values": [
                            "",
                            "myorigin - https://gitee.com/hzy15610046011/cachego.git",
                        ],
                        "children": [],
                    },
                    {
                        "text": "",
                        "values": [
                            "",
                            "origin - https://gitee.com/FishGoddess/cachego.git",
                        ],
                        "children": [],
                    },
                ],
            },
        ]
        # self.set_data(self.tree, data)

    def on_filter(self, filter_text):
        print("filter_text", filter_text)
        data = self.original_data

        def filter_func(node_data: Dict):
            for val in node_data["values"]:
                if filter_text.lower() in val.lower():
                    return True
            for child in node_data["children"]:
                if filter_func(child):
                    return True
            return False

        for item in self.tree.get_children():
            self.tree.delete(item)
        if filter_text:
            self.set_data(self.tree, filter(filter_func, data))
        else:
            self.set_data(self.tree, data)

    def populate_tree(self):
        self.working_thread = threading.Thread(target=self._populate_tree)
        self.working_thread.daemon = True
        self.working_thread.start()

    def _populate_tree(self):

        for i, repo_path in enumerate(
            find_git_repos(self.base_path, self.ignored_paths)
        ):

            local_path_item = self.tree.insert(
                "",
                "end",
                text=str(i + 1),
                values=(repo_path, ""),
            )
            print(f"Git仓库#{i+1}: {os.path.basename(repo_path)}")
            print(f"本地路径: {repo_path}")
            remote_branches = get_remote_urls(repo_path)
            for remote, url in remote_branches:
                print(f"  远程地址: {remote} - {url}")
                self.tree.insert(
                    local_path_item,
                    "end",
                    text="",
                    values=("", f"{remote} - {url}"),
                )
            # if i > 5:
            #     break
            print()

        self.tree.bind("<Double-1>", self.on_item_click)
        self.original_data = self.get_data(self.tree)
        # print(self.get_data(self.tree))

    def open_in_vscode(self):
        item = self.tree.selection()[0]
        repo_path = self.tree.item(item, "values")[0]
        print(repo_path)
        os.system(f"code {repo_path}")

    def get_data(self, tree, parent="", data=None):
        """
        递归获取ttk.Treeview的嵌套数据。

        :param tree: ttk.Treeview实例
        :param parent: 当前遍历的父节点ID
        :param data: 用于递归的内部数据结构
        :return: 嵌套的字典列表
        """
        if data is None:
            data = []
        for child in tree.get_children(parent):
            item = tree.item(child)
            item_data = {"text": item["text"], "values": item["values"], "children": []}
            data.append(item_data)
            self.get_data(tree, child, item_data["children"])
        return data

    def set_data(self, tree, data: List[Dict], parent=""):
        """
        设置树形控件的数据
        """
        # def set_data(tree, data, parent=''):
        """
        将嵌套数据插入到ttk.Treeview中。

        :param tree: ttk.Treeview实例
        :param data: 嵌套的字典列表
        :param parent: 父节点ID
        """
        for item in data:
            # 插入节点
            node_id = tree.insert(
                parent, "end", text=item["text"], values=item["values"]
            )
            # 如果有子节点，递归插入子节点
            if item["children"]:
                self.set_data(tree, item["children"], node_id)

    def on_item_click(self, event):
        item_id = self.tree.focus()
        item_values = self.tree.item(item_id, "values")
        print(f"双击项目: {item_values}")
        # 检查是否为本地路径
        if item_values[0] and os.path.isdir(item_values[0]):
            subprocess.Popen(f'explorer "{item_values[0]}"')
        # 检查是否为远程分支地址
        elif item_values[1]:
            val1, val2 = item_values[1].split("-", maxsplit=1)
            branch_name, branch_url = val1.strip(), val2.strip()
            prefixes = {"git@gitee.com": "https://gitee.com"}
            if branch_url.startswith("http"):
                pass
            elif branch_url.startswith(tuple(prefixes.keys())):
                prefix_key, base_url = branch_url.split(":", maxsplit=1)
                branch_url = urljoin(prefixes[prefix_key], base_url)

            elif branch_url.startswith("git@"):
                branch_url = branch_url.replace(":", "/", 1).replace(
                    "git@", "https://", 1
                )
            else:
                print("Cannot recognize such prefix")
            webbrowser.open(branch_url)


# 使用示例
if __name__ == "__main__":
    root = tk.Tk()
    root.title("Git仓库浏览器")

    base_path = "C:/path/to/git/repos"
    ignored_paths = ["C:/path/to/git/repos/ignore_this_repo"]

    browser = GitRepoBrowser(root, base_path, ignored_paths)
    browser.pack(expand=True, fill="both")

    root.mainloop()
